package com.wang.mongodbstudy.web;

import com.wang.mongodbstudy.dao.UserRepository;
import com.wang.mongodbstudy.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/findAll")
    public void findAll(){
        List<User> userList = userRepository.findAll();
        System.out.println(userList);
    }

    @GetMapping("/insert")
    public void insert(){
        User zhangSan = new User();
        zhangSan.setId("1");
        zhangSan.setName("张三");
        zhangSan.setAge(18);
        System.out.println(userRepository.insert(zhangSan));
        User liSi = new User();
        liSi.setId("2");
        liSi.setName("李四");
        liSi.setAge(19);
        System.out.println(userRepository.insert(liSi));
        User wangWu = new User();
        wangWu.setId("3");
        wangWu.setName("王五");
        wangWu.setAge(20);
        System.out.println(userRepository.insert(wangWu));
    }

    @GetMapping("/delete")
    public void delete(){
        userRepository.deleteAll();
    }
    @GetMapping("update")
    public void update(){
        List<User> userList = userRepository.findByName("张三");
        if(userList != null){
            User zhangSan = userList.get(0);
            zhangSan.setAge(99);
            userRepository.save(zhangSan);
        }

        Optional<User> liSiOptional = userRepository.findOne(new Example<User>() {
            @Override
            public User getProbe() {
                User user = new User();
                user.setName("李四");
                return user;
            }

            @Override
            public ExampleMatcher getMatcher() {
                return ExampleMatcher.matchingAll();
            }
        });
        if(liSiOptional.isPresent()){
            System.out.println(liSiOptional.get());
        }


    }

}
